<template>
    <view id="azm-custom-component" class="cu-custom" :class="{hide:hideNavBar === true}">
        <view class="azm-global-fixed-lr" id="navBarCustom">
            <view :class="mClass" :style="CustomBarStyle" class="flex flex-direction" v-if="!isHideNavigation">
                <view class="status-bar" :style="StatusBarStyle" @click="handleStatusBarClick"/>
                <view class="nav-bar flex-sub" :style="NavBarContentStyle">
                    <block v-if="mode === 'search-custom'">
                        <search-custom :isBack="navigationBar.isBack"
                                       :placeholder="navigationBar.placeholder"
                                       :disabled="navigationBar.disabled"
                                       @search_tap="handleSearchClick" @search_input="_emit"
                                       @search_confirm="_emit" @search_blur="_emit"/>
                    </block>
                    <block v-else-if="mode === 'slot-custom'">
                        <slot name="custom"/>
                    </block>
                    <block v-else>
                        <cu-custom :mode="mode" :isBack="navigationBar.isBack" :title="navigationBar.title"
                                   :backText="navigationBar.backText"
                                   :backType="navigationBar.backType"
                                   @cuBack="handleBack" @cuToHome="handleToHome"/>
                    </block>
                </view>
            </view>
            <slot/>
        </view>
        <view v-if="!fullscreen" :style="NavBarStyle" class="cu-custom-bg"/>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    import cuCustom from './cu-custom.vue'
    import searchCustom from './search-custom.vue'
    import { debounce } from "@u/lodash/throttle"

    export default {
        name: 'nar-bar',
        components: {
            cuCustom,
            searchCustom,
        },
        data () {
            const systemInfo = this.SystemInfo || {};
            const object2style = this.$util.object2style;
            console.log(systemInfo, '+++++4654654646++++++');
            return {
                Custom: {},
                StatusBar: systemInfo.StatusBar,
                CustomBar: systemInfo.CustomBar,
                StatusBarStyle: object2style({height: systemInfo.StatusBar + 'px'}),
                CustomBarStyle: object2style({height: systemInfo.CustomBar + 'px'}),
                NavBarStyle: object2style({height: systemInfo.CustomBar + 'px'}),
                NavBarContentStyle: '',
                HideNavigation: false,
            };
        },
        computed: {
            ...mapState({
                systemInfo: state => state.User.systemInfo
            }),
            navBarStyle () {
                const object2style = this.$util.object2style;
                const {StatusBar, CustomBar, Custom, windowWidth} = this.systemInfo;
                this.setStyle();
            },
            isHideNavigation () {
                let HideNavigation = this.HideNavigation;
                let hideNavigation = this.hideNavigation;
                let hideStatusBar = this.hideStatusBar;
                switch (true) {
                    case HideNavigation === true && hideNavigation === false:
                        return false;
                    case  hideNavigation === true || HideNavigation === true:
                        return true;
                    default:
                        return false;
                }
            },
            navigationBar () {
                const {jude, mapKeys} = this.$util;
                let obj = {};
                let options = !jude.isEmptyObject(this.options, true) ? this.options : {};
                if (jude.isEmpty(options.backgroundColor)) {
                    options.backgroundColor = '#FFFFFF';
                    options.isBackgroundEmpty = true;
                }
                mapKeys(options, obj, true);
                if (!jude.isNumberOfNaN(obj.backType)) obj.backType = 0;
                return obj
            }
        },
        watch: {
            ['systemInfo.CustomBar']: {
                handler () {
                    this.updateNavBarStyle()
                }
            },
            ['fullscreen']: {
                handler () {
                    this.updateNavBarStyle()
                }
            },
            ['slotHeight']: {
                handler () {
                    this.updateNavBarStyle()
                }
            },
        },
        created () {
        },
        mounted () {
            this.updateNavBarStyle()
        },
        props: {
            mClass: {
                type: String,
                default: "bg-white"
            },
            options: {
                type: Object,
                default (data) {
                    return data
                }
            },
            methods: {
                type: Object,
                default (data) {
                    return data
                }
            },
            mode: {
                type: String,
                default: "cu-custom"
            },
            to: String,
            hideNavBar: Boolean,
            fullscreen: Boolean,
            isOnBack: Boolean,
            // 插槽高度 rpx
            slotHeight: {
                type: Number,
                default: 0
            },
        },
        methods: {
            // 更新
            updateNavBarStyle () {
                const systemInfo = this.SystemInfo || {};
                const object2style = this.$util.object2style;
                this.NavBarStyle = object2style({
                    height: systemInfo.CustomBar + uni.upx2px(this.slotHeight) + 'px'
                })
                // 设置容器的高度
                this.setStyle()
            },

            // 后退
            async handleBack (e) {
                const cur = this.$util.getCurrentPage(1);
                const result = await this.handleEventBackOut();
                if (result !== false) {
                    if (cur && cur.route) {
                        this.$$router.back()
                    } else {
                        this.toHome()
                    }
                }
            },
            async handleToHome () {
                const result = await this.handleEventBackOut();
                result !== false && this.toHome();
            },
            toHome () {
                this.$$router.replaceAll('/pages/home/index')
            },
            handleBackOut () {
                let that = this;
                return new Promise(resolve => {
                    that.$emit('onBackOut', function (data) {
                        resolve(data);
                    })
                })
            },
            async handleEventBackOut () {
                let handleBackOut = true;
                if (this.methods && this.methods.handleBackOut) {
                    handleBackOut = this.methods.handleBackOut()
                } else if (this.isOnBack === true) {
                    handleBackOut = await this.handleBackOut()
                }

                if (handleBackOut && handleBackOut.constructor === Promise) {
                    return handleBackOut;
                } else {
                    return Promise.resolve(handleBackOut);
                }
            },
            setStyle: debounce(function () {
                let vm = this;
                const {object2style} = vm.$util;
                const {StatusBar, CustomBar, Custom, windowWidth} = vm.systemInfo;
                const {backgroundColor, color, isBackgroundEmpty, navigationBarTextStyle} = this.navigationBar;
                vm.Custom = Custom;
                let CustomBarStyle = {};
                if (StatusBar > 0) {
                    vm.StatusBar = StatusBar;
                    vm.StatusBarStyle = object2style({height: StatusBar + 'px'})
                }
                if (CustomBar > 0) {
                    vm.CustomBar = CustomBar;
                    CustomBarStyle.height = CustomBar + 'px';
                }
                let fullscreen = this.fullscreen;
                if (backgroundColor && !fullscreen) CustomBarStyle.backgroundColor = backgroundColor;
                else if (fullscreen && isBackgroundEmpty === true)
                    CustomBarStyle.backgroundColor = 'rgba(255,255,255,.2)';
                else CustomBarStyle.backgroundColor = backgroundColor;
                if (color) CustomBarStyle.color = color;
                vm.CustomBarStyle = object2style(CustomBarStyle);
                // #ifdef MP-WEIXIN
                const l = windowWidth - Custom.right;
                vm.NavBarContentStyle = object2style({
                    width: `${Custom.left}px`
                });
                // #endif
                vm.getNavBarCustom();
                // $$$setTimeout(vm.getNavBarCustom, 500);
                let frontColor = "#000000"
                if (['black', 'white'].indexOf(navigationBarTextStyle) > -1) {
                    if (navigationBarTextStyle === "white") {
                        frontColor = "#ffffff"
                    }
                }
                uni.setNavigationBarColor({
                    frontColor: frontColor,
                    backgroundColor: CustomBarStyle.backgroundColor || "#ffffff",
                    // animation: true,
                    complete () {
                        // console.log(arguments, 'setNavigationBarColor');
                    }
                });
            }, 200),
            getNavBarCustom () {
                const that = this;
                const {object2style} = this.$util;
                const SelectorQuery = uni.createSelectorQuery();
                SelectorQuery.in(this);
                const NodesRef = SelectorQuery.select('#navBarCustom').boundingClientRect();
                that.$nextTick(function () {
                    NodesRef.exec(function ([d]) {
                        if (!d) return;
                        that.NavBarStyle = object2style({
                            height: d.height + 'px'
                        });
                        that._emit(d, 'load')
                    });
                })
            },
            handleSearchClick (e) {
                const {jude, mapKeys} = this.$util;
                this._emit(e, 'tap');
                if (!jude.isEmpty(this.to)) this.$$router.push(this.to);
            },
            _emit (e, t) {
                const type = e.type === 'click' ? 'tap' : e.type;
                this.$emit(`navBar${this.firstToUpperCase(t || type)}`, e.detail || e)
            },
            firstToUpperCase (s) {
                return typeof s === "string" ? s.slice(0, 1).toUpperCase() + s.slice(1) : '';
            },
            handleStatusBarClick (e) {
                this._emit(e, 'onStatusBarClick')
                // if()
            }
        }
    }
</script>

<style lang="scss" scoped>
    $nar-bar-height: 44px;
    $status-bar-height: 20px;

    .hide {
        display: none;
    }

    .azm-global-fixed-lr {
        z-index: 800;

        > .flex {
            height: calc(#{$nar-bar-height} + #{$status-bar-height});
        }
    }

    .status-bar {
        width: 100%;
        height: var(--status-bar-height);
        /*background-color: red;*/
    }

    .nav-bar {
        width: 100%;
    }

    .cu-custom-bg {
        height: calc(#{$nar-bar-height} + #{$status-bar-height});
    }
</style>
